package com.online.edu.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.online.edu.course.entity.Category;
import com.online.edu.course.entity.Chapter;
import com.online.edu.course.entity.ChapterPeriod;
import com.online.edu.course.entity.Course;
import com.online.edu.course.entity.Vo.CategoryVo;
import com.online.edu.course.entity.Vo.ChapterVo;
import com.online.edu.course.entity.Vo.PageVo;
import com.online.edu.course.mapper.ChapterMapper;
import com.online.edu.course.service.ICategoryService;
import com.online.edu.course.service.IChapterPeriodService;
import com.online.edu.course.service.IChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 章节表 服务实现类
 * </p>
 *
 * @author world
 * @since 2021-07-30
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements IChapterService {
    @Autowired
    IChapterService chapterService;

    @Autowired
    IChapterPeriodService chapterPeriodService;

    @Override
    public List<ChapterVo> getChapters(PageVo pageVo) {
        QueryWrapper<Chapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id",pageVo.getCourseId());
        //设置当前页和页面大小
        Page<Chapter> page = new Page<>(pageVo.getCurrent(), pageVo.getSize());
        Page<Chapter> coursePage = chapterService.page(page,queryWrapper);
        pageVo.setTotal(Math.toIntExact(coursePage.getTotal()));
        List<Chapter> entities = coursePage.getRecords();

        //把Chapter的数组entities包装成ChapterVo数组
        List<ChapterVo> chapterVos = entities.stream()
                .map(category -> {
                    ChapterVo chapterVo = new ChapterVo();
                    BeanUtils.copyProperties(category, chapterVo);
                    return chapterVo;
                }).collect(Collectors.toList());


        List<ChapterVo> list = chapterVos.stream()
                //.filter( c -> c.getId().equals())
                .map( c ->{
                            //
                            c.setChapterPeriod(getChildrenData(c));
                            return c;
                        })
                .collect(Collectors.toList());
        return list;
    }

    //获取章节下的所有课时数据
    private List<ChapterPeriod> getChildrenData(ChapterVo chapterVo) {
        QueryWrapper<ChapterPeriod> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chapter_id",chapterVo.getId());
        return chapterPeriodService.list(queryWrapper);
    }
}
